package com.example.ams.service;

import com.example.ams.dto.ClockRecordDTO;
import com.example.ams.entity.ClockRecord;
import com.example.ams.entity.Employee;
import com.example.ams.repository.ClockRecordRepository;
import com.example.ams.repository.EmployeeRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 打卡记录服务类
 * Clock Record Service
 */
@Service
public class ClockRecordService {

    @Autowired
    private ClockRecordRepository clockRecordRepository;

    @Autowired
    private EmployeeRepository employeeRepository;

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat DATETIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 查询所有打卡记录
     */
    public List<ClockRecordDTO> findAll() {
        return clockRecordRepository.findAll().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    /**
     * 根据ID查询打卡记录
     */
    public ClockRecordDTO findById(Long id) {
        ClockRecord record = clockRecordRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("打卡记录不存在，ID: " + id));
        return convertToDTO(record);
    }

    /**
     * 根据员工ID查询打卡记录
     */
    public List<ClockRecordDTO> findByEmployeeId(Long employeeId) {
        return clockRecordRepository.findByEmployeeIdOrderByEventTimeDesc(employeeId).stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    /**
     * 根据条件查询打卡记录
     */
    public List<ClockRecordDTO> findByConditions(Long employeeId, String from, String to) {
        try {
            List<ClockRecord> records;

            if (employeeId != null && from != null && to != null) {
                // 按员工和时间范围查询
                Date startTime = parseDateTime(from + " 00:00:00");
                Date endTime = parseDateTime(to + " 23:59:59");
                records = clockRecordRepository.findByEmployeeIdAndTimeRange(employeeId, startTime, endTime);
            } else if (from != null && to != null) {
                // 按时间范围查询所有
                Date startTime = parseDateTime(from + " 00:00:00");
                Date endTime = parseDateTime(to + " 23:59:59");
                records = clockRecordRepository.findByTimeRange(startTime, endTime);
            } else if (employeeId != null) {
                // 只按员工查询
                records = clockRecordRepository.findByEmployeeIdOrderByEventTimeDesc(employeeId);
            } else {
                // 查询所有
                records = clockRecordRepository.findAll();
            }

            return records.stream()
                    .map(this::convertToDTO)
                    .collect(Collectors.toList());
        } catch (ParseException e) {
            throw new RuntimeException("日期格式错误，请使用 yyyy-MM-dd 格式");
        }
    }

    /**
     * 创建打卡记录
     */
    @Transactional
    public ClockRecordDTO create(ClockRecordDTO recordDTO) {
        // 验证员工是否存在
        Employee employee = employeeRepository.findById(recordDTO.getEmployeeId())
                .orElseThrow(() -> new RuntimeException("员工不存在，ID: " + recordDTO.getEmployeeId()));

        ClockRecord record = new ClockRecord();
        BeanUtils.copyProperties(recordDTO, record, "id", "createdAt", "employeeName", "empNo");

        ClockRecord saved = clockRecordRepository.save(record);
        return convertToDTO(saved);
    }

    /**
     * 删除打卡记录
     */
    @Transactional
    public void delete(Long id) {
        if (!clockRecordRepository.existsById(id)) {
            throw new RuntimeException("打卡记录不存在，ID: " + id);
        }
        clockRecordRepository.deleteById(id);
    }

    /**
     * 根据数据来源查询
     */
    public List<ClockRecordDTO> findBySource(ClockRecord.Source source) {
        return clockRecordRepository.findBySourceOrderByEventTimeDesc(source).stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    /**
     * Entity转DTO
     */
    private ClockRecordDTO convertToDTO(ClockRecord record) {
        ClockRecordDTO dto = new ClockRecordDTO();
        BeanUtils.copyProperties(record, dto);

        // 填充员工信息
        employeeRepository.findById(record.getEmployeeId()).ifPresent(employee -> {
            dto.setEmployeeName(employee.getName());
            dto.setEmpNo(employee.getEmpNo());
        });

        return dto;
    }

    /**
     * 解析日期时间
     */
    private Date parseDateTime(String dateTimeStr) throws ParseException {
        return DATETIME_FORMAT.parse(dateTimeStr);
    }

    /**
     * 解析日期
     */
    private Date parseDate(String dateStr) throws ParseException {
        return DATE_FORMAT.parse(dateStr);
    }

    /**
     * 从CSV批量导入打卡记录
     * CSV格式：员工工号,打卡时间,类型,来源,备注
     * 示例：E1001,2025-10-28 09:00:00,IN,DEVICE,正常打卡
     */
    @Transactional
    public int importFromCSV(String csvData) {
        int successCount = 0;
        String[] lines = csvData.split("\n");
        
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i].trim();
            
            // 跳过空行和表头
            if (line.isEmpty() || line.startsWith("员工工号") || line.startsWith("empNo")) {
                continue;
            }
            
            try {
                String[] parts = line.split(",");
                if (parts.length < 3) {
                    continue; // 跳过格式不正确的行
                }
                
                String empNo = parts[0].trim();
                String eventTimeStr = parts[1].trim();
                String eventTypeStr = parts[2].trim();
                String sourceStr = parts.length > 3 ? parts[3].trim() : "DEVICE";
                String remark = parts.length > 4 ? parts[4].trim() : null;
                
                // 根据工号查找员工
                Employee employee = employeeRepository.findByEmpNo(empNo)
                        .orElseThrow(() -> new RuntimeException("员工不存在: " + empNo));
                
                // 创建打卡记录
                ClockRecord record = new ClockRecord();
                record.setEmployeeId(employee.getId());
                record.setEventTime(DATETIME_FORMAT.parse(eventTimeStr));
                record.setEventType(ClockRecord.EventType.valueOf(eventTypeStr.toUpperCase()));
                record.setSource(ClockRecord.Source.valueOf(sourceStr.toUpperCase()));
                record.setRemark(remark);
                
                clockRecordRepository.save(record);
                successCount++;
                
            } catch (Exception e) {
                // 记录错误但继续处理其他行
                System.err.println("导入第 " + (i + 1) + " 行失败: " + e.getMessage());
            }
        }
        
        return successCount;
    }
}

